package com.jbp.controller;

import java.math.BigDecimal;
import java.util.*;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jbp.domin.LuckReq;
import com.jbp.domin.LuckReq2;
import com.jbp.exception.RRException;
import com.jbp.model.*;
import com.jbp.service.*;
import com.jbp.service.impl.LuckPoolRedisService;
import com.jbp.utils.*;
import io.swagger.annotations.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;


/**
 *
 *
 * @author lucheng feng
 * @email retailers@gmail.com
 * @date 2020-06-26 13:49:51
 */
@Api(tags ="APP接口--抽奖" ,hidden = true)
@ApiIgnore
@RestController
@RequestMapping("/rest/lottery")
public class LotteryController {
    @Autowired
    private LotteryService lotteryService;


    @Autowired
    private GiftLotService giftLotService;

    @Autowired
    private GiftService giftService;

    @Autowired
    private WalletRecordService walletRecordService;

    @Autowired
    private  UserService userService;

    @Autowired
    private PropertyService propertyService;

    @Autowired
    private UserDailyLuckRecordService userDailyLuckRecordService;

    @Autowired
    private LuckPoolRedisService luckPoolRedisService;
    @Autowired
    private PoolCritService poolCritService;
    @Autowired
    private ChangeLuckService changeLuckService;
    @Autowired
    private AppConfigService appConfigService;

    @Autowired
    private LuckRankService luckRankService;

    @ApiOperation(value="个人中奖记录",notes="个人中奖记录")
    @ApiResponses({
            @ApiResponse(code = 200,message = "成功",response = Lottery.class),
            @ApiResponse(code = 201,message = "返回失败信息")
    })
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token",value = "token",paramType = "query"),
            @ApiImplicitParam(name="sessionId",value = "sessionId",paramType = "query"),
            @ApiImplicitParam(name="抽奖类型 ",value = "poolType",paramType = "query"),
            @ApiImplicitParam(name="one 单抽 ten 十抽  hundred 百抽",value = "type",paramType = "query"),
            @ApiImplicitParam(name="page",value = "page",paramType = "query"),
    })
    @GetMapping("/personRecord")
    public R personRecord(@RequestParam Map<String, Object> params,@RequestAttribute("userId") Integer userId ){
        params.put("userId",userId);
        //分页参数
        int curPage = 1;
        int limit = 10;
        if(params.get(Constant.PAGE) == null){
            params.put(Constant.PAGE,curPage);
        }
        if(params.get(Constant.LIMIT) == null){
            params.put(Constant.LIMIT,limit);
        }
        curPage = (Integer.parseInt(params.get(Constant.PAGE).toString())-1) *
                Integer.parseInt(params.get(Constant.LIMIT).toString());
        params.put(Constant.PAGE,curPage) ;
        List<Lottery> lotteryList = lotteryService.personRecord(params);
        QueryWrapper<Lottery> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("user_id",params.get("userId"));
        if (params.get("poolType") != null && !params.get("poolType").equals("")){
            queryWrapper.eq("pool_type",params.get("poolType"));
        }
        if (params.get("type") != null && !params.get("type").equals("")){
            queryWrapper.eq("type",params.get("type"));
        }
        int count = lotteryService.personCount(params);
        return R.ok(new PageUtils(lotteryList,count,limit,curPage));
    }


    /**
     * 个人抽奖记录
     * @param params
     * @param userId
     * @return
     */
    @GetMapping("/personLottery")
    public R personLottery(@RequestParam Map<String, Object> params,@RequestAttribute("userId") Integer userId ){
        params.put("userId",userId);
        //分页参数
        int curPage = 1;
        int limit = 10;
        if(params.get(Constant.PAGE) == null){
            params.put(Constant.PAGE,curPage);
        }
        if(params.get(Constant.LIMIT) == null){
            params.put(Constant.LIMIT,limit);
        }
        curPage = (Integer.parseInt(params.get(Constant.PAGE).toString())-1) *
                Integer.parseInt(params.get(Constant.LIMIT).toString());
        params.put(Constant.PAGE,curPage) ;
//        List<Lottery> lotteryList = lotteryService.personRecord(params);
        List<PersonLottery> lotteryList = lotteryService.personLottery(params);

        int count = lotteryService.personLotteryCount(params);
        return R.ok(new PageUtils(lotteryList,count,limit,curPage));
    }

    /**查看暴击奖池*/
    @GetMapping("/getPoolCrit")
    public R getPoolCrit(@RequestParam Map<String, Object> params){
        String poolType = (String) params.get("poolType");
        if (poolType == null ){
            return R.error("参数为空");
        }
        int poolCrit = luckPoolRedisService.getPoolCrit(poolType);

        int normalCrit = poolCritService.getNormalCrit(poolType);
        return R.ok().put("data", poolCrit+normalCrit+160000);
    }

    @ApiOperation(value="查看奖池列表",notes="查看奖池列表")
    @ApiResponses({
            @ApiResponse(code = 200,message = "成功",response = GiftLot.class),
            @ApiResponse(code = 201,message = "返回失败信息")
    })
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token",value = "token",paramType = "query"),
            @ApiImplicitParam(name="sessionId",value = "sessionId",paramType = "query"),
            @ApiImplicitParam(name="抽奖类型 twenty 20钻抽 hundred 100钻抽",value = "poolType",paramType = "query"),
            @ApiImplicitParam(name="one 单抽 ten 十抽  hundred 百抽",value = "type",paramType = "query"),

    })
    @GetMapping("/list")
    public R list(@RequestParam Map<String, Object> params){
        if (params.get("poolType") == null ){
             return R.error("参数为空");
        }
        List<GiftLot> giftLots = giftLotService.poolList((String) params.get("poolType"));
        return R.ok().put("data", giftLots);
    }

    /**
     * 抽奖 新版
     * price 奖池价格
     * times: 次数
     * roomId: 房间id
     * */
    @PostMapping("/luck2")
    public synchronized R luck2(@RequestBody LuckReq2 luckReq, @RequestAttribute("userId") Integer userId) {
        if (luckReq.getRoomId() == null
                || luckReq.getPrice()==null
                || luckReq.getTimes()==null) {
            return R.error("参数不能为空");
        }

        if (!"1".equals(appConfigService.getV("lottery"))) {
            return R.error("敬请期待");
        }

        luckReq.setUserId(userId);
        return lotteryService.luck2(luckReq);
    }

    /**
     * 抽奖
     * poolType: 抽奖类型twenty 20钻抽 hundred 100钻抽
     * type: one 单抽 ten 十抽  hundred 百抽
     * roomId: 房间id
     * */
//    @PostMapping("/luck")
    public synchronized R luck(@RequestBody LuckReq luckReq, @RequestAttribute("userId") Integer userId) {
        if (StringUtils.isEmpty(luckReq.getPoolType())) {
            return R.error("参数不能为空");
        }
        if (StringUtils.isEmpty(luckReq.getType())) {
            return R.error("参数不能为空");
        }
        if (luckReq.getRoomId() == null) {
            return R.error("roomid参数不能为空");
        }

        AppConfig config = appConfigService.getByKey("lottery");
        if (config!=null && "0".equalsIgnoreCase(config.getParamValue())) {
            return R.error("敬请期待");
        }
        //单日抽奖最多5w RMB
        BigDecimal totalPay = userDailyLuckRecordService.getPayToday(userId);
        String luckOneDayStr = propertyService.getV("biggest_luck_one_day");
        if (luckOneDayStr!=null) {
            int luckOneDay = Integer.parseInt(luckOneDayStr);
            if (totalPay!=null && totalPay.compareTo(BigDecimal.valueOf(luckOneDay))>=0) {
                throw new RRException("请明天再试");
            }
        }
        luckReq.setUserId(userId);

        return lotteryService.luck(luckReq);
    }

    @ApiOperation(value="富豪榜单,砸蛋投入量",notes="富豪榜单")
    @ApiResponses({
            @ApiResponse(code = 200,message = "成功",response = GiftLot.class),
            @ApiResponse(code = 201,message = "返回失败信息")
    })
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token",value = "token",paramType = "query"),
            @ApiImplicitParam(name="sessionId",value = "sessionId",paramType = "query"),
            @ApiImplicitParam(name="type 根据当日 day 本周 week 昨日 yesterday ",value = "type",paramType = "query"),
    })
    @GetMapping("/regalList")
    public R regalList(@RequestParam Map<String, Object> params){
        if (params.get("type") != null && params.get("type").equals("")){
            return R.error("参数不能为空");
        }
        List<WalletRecord> walletRecords = walletRecordService.regalList(params);
        walletRecords.forEach(list -> {
            User user = userService.getById(list.getUserId());
            list.setUserName(user.getName());
            list.setUserImg(user.getImg());
        });
        return R.ok(walletRecords);
    }

    /**
     * 手气榜单 按每次砸蛋组合
     * type: one个人 all全部
     * poolType: 奖池
     */
    @GetMapping("/cufflList")
    public R cufflList(@RequestParam Map<String, Object> params,@RequestAttribute("userId") Integer userId){
        params.put("userId",userId);
        PageUtils page = luckRankService.queryPage(params);
        return R.ok().put("data",page);
    }

    @GetMapping("/getChangedConfig")
    public R getChangedConfig(){
        return R.ok().put("data",changeLuckService.getConfig());
    }

    @GetMapping("/luckToday")
    public R smallLuckToday(@RequestAttribute("userId") Integer userId, @RequestParam String poolType){
        return R.ok(userDailyLuckRecordService.getLuckToday(userId, poolType));
    }
}
